package com.inossem.warehousestorage_inossem.activity.in_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inossem.loadandrefresh.PullToRefreshLayout;
import com.inossem.loadandrefresh.pullableview.PullableListView;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.adapter.inStorage.OtherMaterielOverviewAdapter;
import com.inossem.warehousestorage_inossem.bean.inStorage.InStorageOtherBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.InStorageOtherOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.inStorage.InStorageOtherMaterielOverviewRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.InStorageUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import static com.inossem.warehousestorage_inossem.utils.InStorageUtils.getInStorageOtherBean;


//其他入库物料列表
public class InStorageOtherOverviewActivity extends BaseActivity {

    private TextView title, nextStep;

    private PullToRefreshLayout refresh;

    private PullableListView materielList;

    private OtherMaterielOverviewAdapter adapter;

    private String mMaterielCode;

    private List<InStorageOtherOverviewBean.MaterielListBean> allData;

    private InStorageOtherBean otherBean;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_in_storage_other_materiel_overview);
        initView(InStorageOtherOverviewActivity.this);
    }

    @Override
    protected void onResumeImpl() {
        initData(InStorageOtherOverviewActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        materielList = (PullableListView) activity.findViewById(R.id.materielList);
        refresh = (PullToRefreshLayout) activity.findViewById(R.id.materielListRefresh);
        nextStep = (TextView) activity.findViewById(R.id.nextStep);
    }

    private void initData(Activity activity) {
        title.setText(R.string.activity_in_storage_other_index_materiel_detail_material_list);
        ActivityUtils.initBackAndFunction(activity, R.string.activity_in_storage_manage_other_title, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                finish();
            }
        });

        materielList.setPullUpFlag(false);
        materielList.setPullDownFlag(false);
        nextStep.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (check(activity, materielList)) {
                    if (checkItem(activity)) {
                        Intent intent = new Intent(activity, InStorageOtherAddOperatorActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });
        mMaterielCode = "";
        otherBean = getInStorageOtherBean(activity);
        allData = otherBean.getMaterielList() == null ? new ArrayList<>() : otherBean.getMaterielList();
        addMaterielListData(activity, allData, materielList, true);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            getData(activity, mMaterielCode);
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private boolean checkItem(Context context) {
        int confirmNumber = InStorageUtils.getOtherInStorageConfirmNumber(context);
        if (confirmNumber == 0) {
            Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_free_overview_at_least_one_item));
            return false;
        }
        return true;
    }

    private void addMaterielListData(Context context, List<InStorageOtherOverviewBean.MaterielListBean> materielList, ListView listView, boolean flag) {
        if (flag) {
            adapter = new OtherMaterielOverviewAdapter(context, materielList, mMaterielCode, new InStorageOtherOverviewListener() {

                @Override
                public void onNoDoubleClickListener(String materielCode) {
                    if (TextUtils.isEmpty(materielCode)) {
                        Utils.middleToast(context, getResources().getString(R.string.activity_inventory_select_materiel_adapter_material_encoding_must_not_be_empty));
                    } else {
                        mMaterielCode = materielCode;
                        getData(context, mMaterielCode);
                    }
                }

                @Override
                public void deleteMaterielItem(String materielCode) {
                    DialogUtils.getConfirmDialog(context, getResources().getString(R.string.activity_storage_manage_matr_delete_is_enconded_as) + materielCode + getResources().getString(R.string.activity_storage_manage_matr_material), new DialogUtils.ConfirmDialogListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            dialog.cancel();
                            InStorageUtils.deleteOtherMateriel(context, materielCode);
                            otherBean = getInStorageOtherBean(context);
                            allData = otherBean.getMaterielList() == null ? new ArrayList<>() : otherBean.getMaterielList();
                            addMaterielListData(context, allData, InStorageOtherOverviewActivity.this.materielList, true);
                        }
                    }).show();
                }

                @Override
                public boolean onCheckData() {
                    return check(context, listView);
                }
            });
            listView.setAdapter(adapter);
        }
    }

    private boolean check(Context context, ListView listView) {
        int childCount = listView.getChildCount();
        for (int i = 1; i < childCount; i++) {
            View view = listView.getChildAt(i);
            String materielCode = ((TextView) view.findViewById(R.id.materielCode)).getText().toString();
            String inStorageNumber = ((EditText) view.findViewById(R.id.inStorageNumber)).getText().toString();
            String retainDecimal = ((TextView) view.findViewById(R.id.retainDecimal)).getText().toString();
            if (!TextUtils.isEmpty(inStorageNumber) && !RegexUtils.checkDecimal(inStorageNumber)) {
                Utils.middleToast(context,  getResources().getString(R.string.activity_change_storage_materiel_list_material_code) + materielCode + getResources().getString(R.string.activity_in_storage_receive_overview_illegal));
                return false;
            }

            if (!TextUtils.isEmpty(inStorageNumber) && !Utils.checkRetainDecimal(inStorageNumber, retainDecimal)) {
                Utils.middleToast(context, context.getResources().getString(R.string.activity_change_storage_materiel_list_material_code) + materielCode + String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(retainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : retainDecimal));
                return false;
            }

            if (!TextUtils.isEmpty(inStorageNumber) && RegexUtils.checkZero(inStorageNumber)) {
                Utils.middleToast(context, getResources().getString(R.string.activity_change_storage_materiel_list_material_code) + materielCode + getResources().getString(R.string.activity_in_storage_receive_overview_greater_than_zero));
                return false;
            }

            InStorageOtherOverviewBean.MaterielListBean otherInStorageItem = InStorageUtils.getOtherInStorageItemByMaterielCode(context, materielCode);
            if (otherInStorageItem != null) {
                otherInStorageItem.setInStorageNumber(inStorageNumber);
                InStorageUtils.updateOtherInStorageItem(context, otherInStorageItem);
            }
        }
        return true;
    }

    private void getData(Context context, String materielCode) {
        InStorageOtherMaterielOverviewRequest.request(context, materielCode, new GsonBeanListener<InStorageOtherOverviewBean>() {
            @Override
            public void onSuccess(InStorageOtherOverviewBean bean) {
                List<InStorageOtherOverviewBean.MaterielListBean> list = bean.getBody();
                if (list == null || list.isEmpty()) {
                    Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_other_overview_new_data_was_not_found));
                } else {
                    allData = addMateriel(allData, list);
                    otherBean.setMaterielList(allData);
                    Gson gson = new Gson();
                    String json = gson.toJson(otherBean, InStorageOtherBean.class);
                    SPUtils.saveOtherInStorageInformation(context, json);
                    addMaterielListData(context, allData, materielList, true);
                }
            }
        });
    }

    private List<InStorageOtherOverviewBean.MaterielListBean> addMateriel(List<InStorageOtherOverviewBean.MaterielListBean> currentList, List<InStorageOtherOverviewBean.MaterielListBean> addList) {
        if (currentList == null || currentList.isEmpty()) {
            return addList;
        }
        List<InStorageOtherOverviewBean.MaterielListBean> removeList = new ArrayList<>();
        for (int i = 0; i < addList.size(); i++) {
            InStorageOtherOverviewBean.MaterielListBean addItem = addList.get(i);
            for (int j = 0; j < currentList.size(); j++) {
                InStorageOtherOverviewBean.MaterielListBean currentItem = currentList.get(j);
                if (addItem.getMat_code().equals(currentItem.getMat_code())) {
                    removeList.add(addItem);
                }
            }
        }
        addList.removeAll(removeList);
        currentList.addAll(0, addList);
        return currentList;
    }

    public interface InStorageOtherOverviewListener {
        void onNoDoubleClickListener(String materielCode);

        void deleteMaterielItem(String materielCode);

        boolean onCheckData();
    }

}
